<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <areas :area-type="areaType" :areas="treeAreas" v-on:handleNodeClick="onHandleNodeClick"/>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-card>
          <div class="filter-container">
            <el-select v-model="listQuery.unit" class="filter-item" clearable placeholder="单元号"
                       style="margin-left: 20px;width: 110px">
              <el-option
                v-for="item in units"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
            <el-input v-model="listQuery.floor" class="filter-item" clearable placeholder="楼层"
                      style="margin-left: 10px;width: 120px" type="number"></el-input>
            <el-input v-model="listQuery.room_number" class="filter-item" clearable placeholder="门牌号"
                      style="margin-left: 10px;width: 120px" type="number"></el-input>
            <el-input v-model="listQuery.device_number" class="filter-item" clearable
                      placeholder="终端编号" style="margin-left: 10px;width: 140px"></el-input>
            <el-select v-model.trim="listQuery.class" class="filter-item" clearable
                       placeholder="设备类型" style="margin-left: 10px;width: 110px">
              <el-option
                v-for="item in deviceTypes"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
            <el-button v-if="checkPermission('查询设备')" class="filter-item" icon="el-icon-search" style="margin-left:40px"
                       type="primary"
                       @click="getDeviceList">
              查询
            </el-button>
            <el-button v-if="checkPermission('导出设备')" :loading="btnLoading" class="filter-item"
                       icon="el-icon-download" style="margin-left: 10px" type="primary" @click="exportDevices">
              导出 
            </el-button>
            <el-button v-if="checkPermission('导出设备')"  class="filter-item"
                       icon="el-icon-upload" style="margin-left: 10px" type="primary" @click="batchUpdateDevice">
              批量更新
            </el-button>
          </div>
            <div class="filter-container">
            <el-dropdown v-if="checkPermission('添加设备')" class="filter-item" style="margin-left: 20px"
                         @command="menuCommand">
              <el-button type="primary">
                <i class="el-icon-plus"></i>
                新建<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="door">户表</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-dropdown class="filter-item" style="margin-left: 10px" @command="menuCommand">
              <el-button type="primary">
                批量操作<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-if="checkPermission('删除设备')" command="del">删除</el-dropdown-item>
                <!--                <el-dropdown-item command="time">时间校准</el-dropdown-item>-->
                <!--                <el-dropdown-item command="open">开阀</el-dropdown-item>-->
                <!--                <el-dropdown-item command="close">关阀</el-dropdown-item>-->
                <!--                <el-dropdown-item command="rate">修改N上传频率</el-dropdown-item>-->
                <!--                <el-dropdown-item command="cfg">模式配置</el-dropdown-item>-->
              </el-dropdown-menu>
            </el-dropdown>
            <el-upload
              class="filter-item"
                action=""
                :before-upload="handleReaderFileDelete"
                accept=".xlsx,.xls"
                :limit="1"
              style="display: inline-block;margin-left: 20px;"
              ref="upload">
              <el-button slot="trigger" :loading="btnLoading"  type="primary"><i class="el-icon-upload el-icon--left"></i>导入删除</el-button>
            </el-upload>
          </div>
          <div class="app-container">
            <el-table
              :key="tableKey"
              ref="equipTable"
              v-loading="listLoading"
              :cell-style="{padding:0+'px'}"
              :data="list"
              :row-style="{height:40+'px'}"
              border
              fit
              height="700"
              highlight-current-row
              stripe
              style="width: 100%;"
            >
              <el-table-column
                type="selection"
                width="40">
              </el-table-column>
              <el-table-column
                type="index"
                width="50">
              </el-table-column>
              <el-table-column align="center" label="终端编号">
                <template v-slot="{row}">
                  <span>{{ row.terminal_number }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="所属账户">
                <template v-slot="{row}">
                  <span>{{ row.user.username || '-'  }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="设备类型">
                <template v-slot="{row}">
                  <span>{{ row.class }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="设备版本" width="80">
                <template v-slot="{row}">
                  <span>{{ row.version }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="口径" width="80">
                <template v-slot="{row}">
                  <span>{{ row.size }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="最新抄表时间">
                <template v-slot="{row}">
                  <span>{{ formatDate(row.last_meter_time) }}</span>
                </template>
              </el-table-column>
              <el-table-column align="left" label="安装地址">
                <template v-slot="{row}">
                  <span>{{ row.install_address }}</span>
                </template>
              </el-table-column>

              <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="200">
                <template v-slot="{row,$index}">
                  <el-button v-if="checkPermission('修改设备')" circle icon="el-icon-edit" type="primary"
                             @click="updateDevice(row)">
                  </el-button>
                  <el-button v-if="checkPermission('更换设备')" circle icon="el-icon-refresh" title="换表" type="primary"
                             @click="replaceDevice(row)">
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <pagination v-show="total>0" :limit.sync="listQuery.pageSize" :page.sync="listQuery.page" :total="total"
                        @pagination="getDeviceList"/>

            <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible"
                       custom-class="window-small-width">
              <el-form ref="dataForm" :model="temp" :rules="rules" label-position="right" label-width="80px"
              >
                <el-form-item label="所属楼栋" prop="area">
                  <area-selector ref="areaSelector" :area-type="areaType" :areas="treeAreas"
                                 :disable="editStatus || replaceStatus" :value="temp.area_path"
                                 v-on:selectArea="onSelectArea"></area-selector>
                </el-form-item>
                <el-form-item label="所属用户" prop="customer_id">
                  <el-select v-model="temp.customer_id" :disabled="editStatus || replaceStatus" clearable filterable
                             placeholder="请选择">
                    <el-option
                      v-for="item in customerList"
                      :key="item.id"
                      :label="item.room_number"
                      :value="item.id">
                      <span style="float: left">{{ item.room_number }}</span>
                      <span style="float: right; color: #8492a6; font-size: 13px">{{ item.unit }}</span>
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="设备类型" prop="class">
                  <el-select v-model="temp.class" :disabled="editStatus || replaceStatus" clearable placeholder="设备类型">
                    <el-option
                      v-for="item in deviceTypes"
                      :key="item"
                      :label="item"
                      :value="item">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="协议版本" prop="version">
                  <el-select v-model="temp.version" :disabled="editStatus || replaceStatus" clearable placeholder="设备类型">
                    <el-option
                      v-for="item in xieYi"
                      :key="item"
                      :label="item"
                      :value="item">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="终端编号" prop="terminal_number">
                  <el-input v-model="temp.terminal_number" :disabled="editStatus" size="200"/>
                  <el-alert
                    v-if="replaceStatus"
                    :closable="false"
                    :title="'旧:'+oldDevice.terminal_number"
                    show-icon
                    type="info">
                  </el-alert>
                </el-form-item>
                <el-form-item label="安装地址" prop="install_address">
                  <el-input v-model="temp.install_address"/>
                </el-form-item>
                <el-form-item label="安装时间" prop="install_date">
                  <el-date-picker
                    v-model="temp.install_date"
                    placeholder="选择日期"
                    value-format="yyyyMMdd"
                    type="date">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="口径大小" prop="device_size">
                  <el-select v-model="temp.size" clearable placeholder="请选择">
                    <el-option
                      v-for="item in deviceSize"
                      :key="item"
                      :label="item"
                      :value="item">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="允许关机" prop="is_allowed_close_cmd">
                 <el-select v-model="temp.is_allowed_close_cmd" clearable placeholder="请选择">
                    <el-option
                      v-for="item in [{label:'是',value:true},{label:'否',value:false}]"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="初始流量" prop="start_amount">
                  <el-input v-model="temp.start_amount" type="number">
                    <template v-slot="append">m³</template>
                  </el-input>
                </el-form-item>
                <el-form-item label="备注" label-width="80px" prop="remark">
                  <el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入"
                            type="textarea"/>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">
                  取消
                </el-button>
                <el-button :loading="btnLoading" type="primary" @click="handleForm">
                  确认
                </el-button>
              </div>
            </el-dialog>
            <el-dialog :visible.sync="dialogCommandVisible" title="指令下发">
              <el-form ref="commandForm" :model="temp" :rules="rules" label-position="right" label-width="100px"
                       style="width: 400px; margin-left:50px;">
                <el-form-item v-if="command.cmd === 5" label="洗阀模式" prop="zerocheck">
                  <el-switch
                    v-model="command.params.zerocheck"
                    :active-value="activeValue"
                    :inactive-value="inactiveValue"
                    active-color="#13ce66"
                    inactive-color="#ff4949">
                  </el-switch>
                </el-form-item>
                <el-form-item v-if="command.cmd === 4" label="上传频率" prop="model">
                  <el-input v-model="command.params.rate" suffix-icon="el-icon-alarm-clock" type="number"/>
                </el-form-item>
                <el-form-item v-if="command.cmd === 4" label="上传时间" prop="model">
                  <el-time-select
                    v-model="command.params.time"
                    :picker-options="{
                      start: '00:00',
                      step: '00:10',
                      end: '24:00'
                    }"
                    placeholder="选择时间">
                  </el-time-select>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogCommandVisible = false">
                  取消
                </el-button>
                <el-button :loading="btnLoading" type="primary" @click="orderCommand">
                  确认
                </el-button>
              </div>
            </el-dialog>
            <el-dialog :visible.sync="dialogLogVisible" title="操作记录">
              <el-timeline :reverse="reverse">
                <el-timeline-item
                  v-for="(activity, index) in deviceLogs"
                  :key="index"
                  :timestamp="activity.time_stamp"
                  placement="top">
                  <el-card>
                    <h3>{{ activity.title }}</h3>
                    <h4>{{ activity.content }}</h4>
                    <p>{{ activity.operator }} 操作于 {{ activity.create_time }}</p>
                  </el-card>
                </el-timeline-item>
              </el-timeline>
            </el-dialog>
            <el-dialog :visible.sync="dialogBatchUpdateVisible" title="批量更新">
              <el-upload
                action=""
                :before-upload="handleReaderFile"
                accept=".xlsx,.xls"
                :limit="1"
              >
                <div slot="tip" class="el-upload__tip">{{batchUpdate.filename}}</div>
                <el-button type="primary">上传 Excel 文件</el-button>
              </el-upload>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogBatchUpdateVisible = false">
                  取消
                </el-button>
                <el-button :loading="btnBatchLoading" type="primary" @click="handleBatchUpdate">
                  确认
                </el-button>
              </div>
            </el-dialog>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import areas from '@/components/area/AreaTree'
import AreaSelector from '@/components/area/AreaSelector'
import Pagination from '@/components/Pagination'
import {
  addDevice, batchUpdateDevice,
  deleteDevice,
  batchDelete,
  exchange,
  exportDevices,
  getDeviceList,
  sendCommand,
  updateDevice,
  weeklyMeter
} from "@/api/device";
import {getCustomerList} from "@/api/customer";
import {getAreaTree} from "@/api/area";
import LineChart from "./components/LineChart";
import {checkPermission} from "@/utils/permission"
import moment from "moment";
import {exportExcel} from "@/utils/excel";
import XLSX from "xlsx";


export default {
  name: 'device-list',
  components: {AreaSelector, areas, Pagination, LineChart},
  data() {
    const validateArea = (rule, value, callback) => {
      if (this.temp.area_code === '') {
        callback(new Error('请选择楼栋'))
      } else {
        callback()
      }
    }
    return {
      dialogFormVisible: false,
      dialogCommandVisible: false,
      dialogLogVisible: false,
      dialogBatchUpdateVisible: false,
      dialogStatus: 'create',
      btnLoading: false,
      btnBatchLoading: false,
      tableKey: 0,
      activeValue: 1,
      inactiveValue: 0,
      deviceLogs: [],
      reverse: true,
      exportData: [],
      listLoading: true,
      list: [],
      chartData: {},
      areaType: 2,
      workModels: [{name: '线断', value: 1}, {name: '检定模式', value: 2}, {name: '洗阀模式', value: 3}],
      command: {
        ids: [],
        params: {zerocheck: 0, upvalveopen: 0, calibration: 0, rate: 1, time: '18:30', minite: '', hour: ''},
        cmd: 0
      },
      deviceVersions: [
        {label: "1.1", value: '1.1'}
      ],
      batchUpdate:{
        filename:'',
        deviceNumber:0,
        data:[],
      },
      deviceSize: [15, 20, 25, 32, 40, 50, 65, 80, 100, 125, 150, 200, 250, 300],
      temp: {
        id: 0,
        area_code: '',
        area_name: '',
        area_path: [],
        class: '',
        version: '',
        name: "",
        customer_id: '',
        size: 15,
        terminal_number: '',
        install_address: '',
        install_date: '',
        start_duration: 0,
        start_amount: 0,
        status: 0,
        is_allowed_close_cmd:false
      },
      treeAreas: [],
      oldDevice: {},
      xieYi:[
        'CSB-NB-FK-V01',
        'CSB-NB-WF-V01',
        'CSB-CAT1-FK-V01',
        'CSB-CAT1-WF-V01',
        'ZNB-NB-FK-V01',
        'ZNB-NB-WF-V01',
        'ZNB-CAT1-FK-V01',
        'ZNB-CAT1-WK-V01',
        'CSB-NB-FK-V51',
        'CSB-NB-WF-V51',
        'CSB-CAT1-FK-V51',
        'CSB-CAT1-WK-V51'
      ],
      total: 0,
      textMap: {
        update: '编辑设备',
        create: '新建设备',
        replace: '更换设备',
      },
      listQuery: {
        area_code: '',
        category: this.$store.getters.deviceCategory,
        device_number: '',
        class: '',
        unit: '',
        floor: '',
        room_number: '',
        is_contains_sub: this.$store.getters.showSubData,
        page: 1,
        pageSize: 20,
      },
      units: ['一单元', '二单元', '三单元', '四单元', '五单元', '六单元', '七单元', '八单元', '九单元', '十单元'],
      customerList: [],
      rules: {
        install_date: [{required: true, message: '请选择安装日期', trigger: 'blur'}],
        terminal_number: [{required: true, message: '终端号必填', trigger: 'blur'}],
        version: [{required: true, message: '协议版本必填', trigger: 'blur'}],
        class: [{required: true, message: '请选择设备类型', trigger: 'change'}],
        customer: [{required: true, message: '请关联用户', trigger: 'change'}],
        area: [{validator: validateArea, required: true, trigger: 'change'}]
      }
    };
  },
  created() {
    this.getDeviceList()
    this.getAreaTree()
  },
  computed: {
    editStatus() {
      return this.dialogStatus === 'update'
    },
    replaceStatus() {
      return this.dialogStatus === 'replace'
    },
    deviceTypes() {
      const c  = this.$store.getters.deviceCategory
      return this.$store.getters.deviceType[c]
    }
  },
  methods: {
    handleReaderFileDelete(file){
      // this.batchUpdate.filename = file.name
      // 使用 FileReader 读取文件
      const reader = new FileReader();
      const that = this
      that.btnLoading = true
      reader.onload = (e) => {
        const data = e.target.result;
        // 使用 XLSX 解析 Excel 文件内容
        const workbook = XLSX.read(data, { type: "binary" });
        // 获取第一个工作表的内容
        const firstSheetName = workbook.SheetNames[0];

        const worksheet = workbook.Sheets[firstSheetName];
        // 将工作表内容解析为 JSON
        const fileData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
        let rawData = typeof fileData[0][0] === 'number'?fileData:fileData.slice(1);
        if (rawData.length === 0) {
          that.$message.error('批量更新最数为1')
          that.btnLoading = false
          return false
        }
        if (rawData.length > 100) {
          that.$message.error('批量更新最大数为100')
          that.btnLoading = false
          return false
        }
        rawData = rawData.map((row) => row.map((cell) => String(cell || "")));
        let pool = [];
        for (let i = 0; i < rawData.length; i++) {
          for (let j = 0; j < rawData[i].length; j++) {
            pool.push(rawData[i][j]);
          }
        }
        batchDelete({"terminal_numbers": pool}).then(response => {
          if (response.code === 20000) {
            that.$message.success("删除成功")
            that.getDeviceList()
            that.btnLoading = false
          } else {
            that.btnLoading = false
            that.$message.error('删除失败')
          }
        })
      };

      // 以二进制方式读取文件
      reader.readAsBinaryString(file);

      // 阻止默认上传行为
      return false;
    },
    checkPermission,
    exportDevices() {
      this.btnLoading = true
      const exportQueryData = Object.assign({}, this.listQuery)
      exportQueryData.pageSize = 5000
      getDeviceList(exportQueryData).then(response => {
        const headers = [
          '用户姓名','水司编号','用户类型','单元号',
          '楼层','室号','证件编号','设备类型','协议版本',
          '终端编号','口径尺寸','安装地址描述','安装时间',
          '初始流量','手机','是否启用下发关机指令'
        ]
        const cType = [{name: '居民', value: 1},{name: '商业', value: 2},{name: '工业', value: 3},{name: '民用', value: 4},{name: '其他', value: 0}]
        const data = response.data.list.map(item => ({
          用户姓名: item.customer ? item.customer.customer_name : '未知',
          水司编号: item.customer ? item.customer.refer_number: '未知',
          用户类型: item.customer ? cType.find(t => t.value === item.customer.customer_type).name : '未知',
          单元号: item.customer ? item.customer.unit : '未知',
          楼层: item.customer ? item.customer.floor : '未知',
          室号: item.customer ? item.customer.room_number : '未知',
          证件编号: item.customer? item.customer.identity_card : '未知',
          设备类型: item.class,
          协议版本: item.version,
          终端编号: item.terminal_number,
          口径尺寸: item.size,
          安装地址描述: item.install_address,
          安装时间: item.install_date,
          初始流量: item.start_amount,
          手机: item.customer? item.customer.mobile : '未知',
          是否启用下发关机指令: item.is_allowed_close_cmd ? '是' : '否',
        }))
        exportExcel(data, headers, '设备数据-'+moment().format('YYYYMMDD'))
        setTimeout(() => {
          this.btnLoading = false
        }, 1.5 * 1000)
      }).catch(err => {

      })
      this.listLoading = false
    },
    getAreaTree() {
      getAreaTree({type: 2,is_contains_sub:this.$store.getters.showSubData}).then(response => {
        this.treeAreas = response.data
      })
    },
    analysis(row) {
      this.chartData = {}
      weeklyMeter({id: row.id}).then(resp => {
        if (resp.code === 20000) {
          this.dialogBatchUpdateVisible = true
          this.chartData = resp.data
        }
      })
    },
    menuCommand(cmd) {
      this.command.ids = []
      this.command.params = {rate: 1, model: 0, status: 0}
      switch (cmd) {
        case 'del':
          this.handleDelete()
          break
        case 'time':
          this.sendCmd(1)
          break
        case 'open':
          this.command.params.status = 1
          this.sendCmd(2)
          break
        case 'close':
          this.sendCmd(2)
          break
        case 'off':
          this.sendCmd(3)
          break
        case 'rate':
          this.sendCmd(4)
          break
        case 'cfg':
          this.sendCmd(5)
          break
        case 'door':
          this.createDevice()
      }
    },
    handleForm() {
      switch (this.dialogStatus) {
        case 'create':
          this.handleCreate();
          break
        case 'update':
          this.handleUpdate()
          break
        case 'replace':
          this.handleReplaceDevice()
          break
      }
    },
    sendCmd(cmd) {
      this.command.cmd = cmd
      let selectRows = this.$refs.equipTable.selection
      let ids = []
      selectRows.forEach(function (row) {
        ids.push(row.id)
      })
      this.command.ids = ids
      if (this.command.ids.length === 0) {
        this.$message.warning('请勾选设备')
        return
      }
      if (cmd < 4) {
        this.$confirm('是否确认发送命令', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          sendCommand(this.command).then(response => {
            if (response.code === 20000) {
              this.$notify({
                title: 'Success',
                message: '操作成功',
                type: 'success',
                duration: 3000
              })
            } else {
              this.$notify({
                title: 'Failed',
                message: response.message,
                type: 'error',
                duration: 3000
              })
            }
          })
        })
      } else {
        this.dialogCommandVisible = true
      }
    },
    orderCommand() {
      let data = Object.assign({}, this.command)
      data.params.rate = parseInt(data.params.rate)
      if (data.cmd === 4) {
        let t = data.params.time.split(':')
        if (t.length < 2) {
          this.$message.error('上传时间设置错误')
          return
        }
        data.params.hour = t[0]
        data.params.minite = t[1]
      }
      this.btnLoading = true
      sendCommand(data).then(response => {
        if (response.code === 20000) {
          this.$notify({
            title: 'Success',
            message: '命令下达成功',
            type: 'success',
            duration: 3000
          })
          this.dialogCommandVisible = false
        } else {
          this.$notify({
            title: 'Failed',
            message: response.message,
            type: 'error',
            duration: 3000
          })
        }
      })
      this.btnLoading = false
    },
    onHandleNodeClick: function (data) {
      if (this.listQuery.area_code !== data.code) {
        this.listQuery.area_code = data.code
        this.getDeviceList()
      }
    },
    getDeviceList() {
      this.listLoading = true
      let queryData = Object.assign({}, this.listQuery)
      queryData.device_size = queryData.device_size || 0
      getDeviceList(queryData).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    replaceDevice(row) {
      this.dialogStatus = 'replace'
      this.dialogFormVisible = true
      this.temp = Object.assign({}, row)
      this.temp.area_path = this.temp.area_path.split(',')
      this.oldDevice = Object.assign({}, row)
      this.dialogFormVisible = true
      this.fetchCustomers()
      this.$nextTick(() => {//等待子组件mount再执行
        this.$refs['areaSelector'].setSelectedNodes(this.temp.area_path)
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleReplaceDevice() {
      this.btnLoading = true
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.start_amount = parseFloat(tempData.start_amount)
          tempData.start_duration = parseInt(tempData.start_duration)
          exchange(tempData).then(response => {
            if (response.code === 20000) {
              this.$notify({
                title: 'Success',
                message: '更换成功',
                type: 'success',
                duration: 3000
              })
              this.dialogFormVisible = false
              this.getDeviceList()
            } else {
              this.$notify({
                title: 'Failed',
                message: response.message,
                type: 'error',
                duration: 3000
              })
            }
          })
        }
      })
      this.btnLoading = false
    },
    createDevice() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['areaSelector'].setSelectedNodes([])
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateDevice(row) {
      this.resetTemp()
      this.dialogStatus = 'update'
      this.temp = Object.assign({}, row)
      this.temp.area_path = this.temp.area_path.split(',')
      this.dialogFormVisible = true
      this.fetchCustomers()
      this.$nextTick(() => {//等待子组件mount再执行
        this.$refs['areaSelector'].setSelectedNodes(this.temp.area_path)
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate() {
      this.btnLoading = true
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.start_amount = parseFloat(tempData.start_amount)
          tempData.start_duration = parseInt(tempData.start_duration)
          updateDevice(tempData).then(response => {
            if (response.code === 20000) {
              this.$notify({
                title: 'Success',
                message: '更新成功',
                type: 'success',
                duration: 3000
              })
              this.dialogFormVisible = false
              this.getDeviceList()
            } else {
              this.$notify({
                title: 'Failed',
                message: '更新失败',
                type: 'error',
                duration: 3000
              })
            }
          })
        }
      })
      this.btnLoading = false
    },
    handleCreate() {
      this.btnLoading = true
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          tempData.area_path = tempData.area_path.join(',')
          tempData.start_amount = parseFloat(tempData.start_amount)
          tempData.start_duration = parseInt(tempData.start_duration)
          addDevice(tempData).then(response => {
            if (response.code === 20000) {
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: '设备创建成功',
                type: 'success',
                duration: 3000
              })
              this.dialogFormVisible = false
            } else {
              this.$notify({
                title: 'Failed',
                message: response.message,
                type: 'success',
                duration: 3000
              })
            }
          })
        }
      })
      this.btnLoading = false
    },
    handleDelete() {
      let selectRows = this.$refs.equipTable.selection
      let ids = []
      selectRows.forEach(function (row) {
        ids.push(row.id)
      })
      if (ids.length === 0) {
        this.$message.warning('请勾选需要删除的设备')
        return
      }
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDevice({ids: ids}).then(response => {
          if (response.code === 20000) {
            this.$notify({
              title: 'Success',
              message: '成功删除',
              type: 'success',
              duration: 3000
            })
            this.getDeviceList()
          } else {
            this.$notify({
              title: 'Failed',
              message: '无法删除',
              type: 'error',
              duration: 3000
            })
          }
        })
      })

    },
    fetchCustomers() {
      getCustomerList({"area_code": this.temp.area_code,"page":1,"pageSize":1000}).then(response => {
        if (response.code === 20000) {
          this.customerList = response.data.list
          this.customerList.push({id: 0, room_number: '请选择'})
        } else {
          this.$message.error('读取用户数据错误')
          this.customerList = []
        }
      })
    },
    onSelectArea(data) {
      if (data !== '') {
        this.temp.area_path = data.path
        this.temp.area_code = data.value
        this.temp.area_name = data.pathLabels.join('/')
        getCustomerList({"area_code": this.temp.area_code,"page":1,"pageSize":1000}).then(response => {
          if (response.code === 20000) {
            this.customerList = response.data.list
          } else {
            this.$message.error('读取数据错误')
            this.customerList = []
          }
        })
      } else {
        this.temp.area_path = ''
        this.temp.area_code = ''
        this.temp.area_name = ''
        this.customerList = []
      }
    },
    batchUpdateDevice() {
      this.dialogBatchUpdateVisible = true;
    },
    handleReaderFile(file){
      this.batchUpdate.filename = file.name
      // 使用 FileReader 读取文件
      const reader = new FileReader();
      const that = this
      reader.onload = (e) => {
        const data = e.target.result;

        // 使用 XLSX 解析 Excel 文件内容
        const workbook = XLSX.read(data, { type: "binary" });

        // 获取第一个工作表的内容
        const firstSheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[firstSheetName];

        // 将工作表内容解析为 JSON
        const fileData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
        let rawData = fileData.slice(1);
        let filteredRows = rawData.filter((row) => {
          // 如果第八列不存在，或者为空字符串或 null/undefined，则过滤掉
          return row[9] !== undefined && row[9] !== null && row[9].toString().trim() !== "";
        });
        if (filteredRows.length === 0) {
          that.$message.error('批量更新最小设备数为1')
          return false
        }
        if (filteredRows.length > 100) {
          that.$message.error('批量更新最大设备数为100')
          return false
        }
        filteredRows = filteredRows.map((row) => row.map((cell) => String(cell || "")));
        that.batchUpdate.data = filteredRows;
      };

      // 以二进制方式读取文件
      reader.readAsBinaryString(file);

      // 阻止默认上传行为
      return false;
    },
    handleBatchUpdate() {
      this.btnBatchLoading = true
      const batchData = {
        rows:this.batchUpdate.data
      }
      batchUpdateDevice(batchData).then(res => {
        this.btnBatchLoading = false
        if(res.code === 20000) {
          this.$message.success("批量更新完成")
        }else{
          this.$message.error(resp.message)
        }
      }).catch(e => {
        this.btnBatchLoading = false
        this.$message.error(e)
      })
    },
    formatType(row) {
      let s = ''
      this.deviceTypes.forEach(function (type) {
        if (type.value === row.class) {
          s = type.label
        }
      })
      return s
    },
    formatDate(dateStr) {
      const d = moment(dateStr)
      if (d.millisecond() === 0) {
        return '-'
      }
      return d.format('YYYY-MM-DD')
    },
    resetTemp() {
      this.temp = {
        id: 0,
        area_code: '',
        area_name: '',
        area_path: [],
        class: '',
        version: '',
        name: "",
        customer_id: '',
        size: 15,
        install_address: '',
        install_date: '',
        start_amount: 0,
        status: 0,
        terminal_number: '',
        is_allowed_close_cmd:false
      }
    },
    resetQueryParams() {
      this.listQuery = {
        id: 0,
        page: 1,
        pageSize: 20,
        name: ''
      }
    }
  }
}
</script>
